package org.zwy.gradetrack.event;

import lombok.RequiredArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.zwy.gradetrack.entity.GraduationRequirementAchievement;
import org.zwy.gradetrack.service.DirectEvaluationService;
import org.zwy.gradetrack.service.GraduateSelfEvaluationService;
import org.zwy.gradetrack.service.GraduationRequirementAchievementService;
import org.zwy.gradetrack.service.TeacherEvaluationService;

import java.math.BigDecimal;
import java.time.LocalDateTime;

@Component
@RequiredArgsConstructor
public class AchievementCalculationEventListener {

    private final GraduationRequirementAchievementService achievementService;
    private final DirectEvaluationService directEvaluationService;
    private final GraduateSelfEvaluationService selfEvaluationService;
    private final TeacherEvaluationService teacherEvaluationService;

    @EventListener
    public void handleAchievementCalculation(AchievementCalculationEvent event) {
        Long indicatorId = event.getIndicatorId();
        Integer evaluationYear = event.getEvaluationYear();

        // 获取或创建达成度记录
        GraduationRequirementAchievement achievement = achievementService.lambdaQuery()
                .eq(GraduationRequirementAchievement::getIndicatorId, indicatorId)
                .eq(GraduationRequirementAchievement::getEvaluationYear, evaluationYear)
                .one();

        if (achievement == null) {
            achievement = new GraduationRequirementAchievement();
            achievement.setIndicatorId(indicatorId);
            achievement.setEvaluationYear(evaluationYear);
            achievement.setCreateTime(LocalDateTime.now());
        }

        // 获取直接评价数据
        BigDecimal directEvaluation = directEvaluationService.getLatestEvaluationScore(indicatorId, evaluationYear);
        if (directEvaluation != null) {
            achievement.setDirectEvaluation(directEvaluation);
        }

        // 获取毕业生自评数据
        BigDecimal selfEvaluation = selfEvaluationService.getLatestEvaluationScore(indicatorId, evaluationYear);
        if (selfEvaluation != null) {
            achievement.setGraduateSelfEval(selfEvaluation);
        }

        // 获取教师评价数据
        BigDecimal teacherEvaluation = teacherEvaluationService.getLatestEvaluationScore(indicatorId, evaluationYear);
        if (teacherEvaluation != null) {
            achievement.setTeacherEval(teacherEvaluation);
        }

        // 计算综合评价值
        achievementService.calculateComprehensiveScore(achievement);
        achievement.setUpdateTime(LocalDateTime.now());

        // 保存或更新达成度记录
        if (achievement.getId() == null) {
            achievementService.save(achievement);
        } else {
            achievementService.updateById(achievement);
        }
    }
} 